import pyautogui
import subprocess
import os
import time

file_path = os.path.abspath(__file__)
work_dir = os.path.join(os.path.dirname(file_path), 'work')


def check_work_dir():
    if not os.path.exists(work_dir):
        os.makedirs(work_dir)


check_work_dir()


def create_file(file_name, content):
    file_path_name = os.path.join(work_dir, file_name)
    with open(file_path_name, 'w', encoding='utf-8') as f:
        f.write(content)
        f.close()
        print(f"文件创建成功，保存路径：{file_path_name}")


def use_subprocess(optionsList):

    if (type(optionsList) == str):
        optionsList = optionsList.split(" ")
    try:
        print(f"执行command: {optionsList}")
        res = subprocess.getoutput(optionsList)
        return res
    except subprocess.CalledProcessError as e:
        return e.output


def move_and_click(x, y):
    x = int(x)
    y = int(y)
    move_mouse(x, y)
    click_mouse()


def move_mouse(x, y):
    x = int(x)
    y = int(y)
    pyautogui.moveTo(x, y)
    print(f"鼠标移动到：{x},{y}")


def click_mouse():
    pyautogui.click()
    print("鼠标点击")


def click_right_mouse():
    pyautogui.click(button='right')
    print("鼠标右键点击")


def input_text(text):
    pyautogui.typewrite(text)
    print(f"输入文本：{text}")


def press_key(key):
    pyautogui.press(key)
    print(f"按下按键：{key}")


def keyDown(key):
    pyautogui.keyDown(key)


def keyUp(key):
    pyautogui.keyUp(key)


def hotKey(keys):
    list_keys = keys.split("+")
    for item in list_keys:
        keyDown(item)
    time.sleep(0.1)
    for item in list_keys[::-1]:
        keyUp(item)
    print(f"按下组合键：{keys}")


def screenshotAll():
    file_path_name = os.path.join(work_dir, time.strftime(
        "%Y-%m-%d_%H-%M-%S", time.localtime()) + '_ALL.png')
    img = pyautogui.screenshot()
    img.save(file_path_name)
    print(f"截图成功，保存路径：{file_path_name}")


def screenshot(x, y, w, h):
    x = int(x)
    y = int(y)
    w = int(w)
    h = int(h)
    img = pyautogui.screenshot(region=(x, y, w, h))
    file_path_name = os.path.join(work_dir, time.strftime(
        "%Y-%m-%d_%H-%M-%S", time.localtime()) + '.png')
    img.save(file_path_name)
    print(f"截图成功，保存路径：{file_path_name}")


def system_info():
    width, height = pyautogui.size()
    return f"{width}x{height}"
